package com.example.hy2110szyx.controller;

import com.example.hy2110szyx.common.MyJsonResult;
import com.example.hy2110szyx.entity.UserInfo;
import com.example.hy2110szyx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
@RequestMapping(value = "/user", produces = "application/json")
@Slf4j
@CrossOrigin(origins = "*")
public class UserLoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public MyJsonResult regist(@RequestBody UserInfo user) {
        UserInfo existsUser = null;
        String uno = null;//用户编号
        UserInfo userInfo = userService.queryByUsername(user.getUsername());
        if (null != userInfo) {
            return new MyJsonResult(1, "该用户名已被注册", null, null);
        }
        do {
            //防止用户编号重复
            uno = ((int)(Math.random()*9+1)*1000000) + "";
            existsUser = userService.queryByUno(uno);
        } while (null != existsUser);
        user.setUno(uno);
        userService.regist(user);
        return new MyJsonResult(0, "注册成功", null, null);
    }

    @GetMapping("/checkUser/{name}/{pwd}")
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public MyJsonResult checkUser(@PathVariable("name") String name, @PathVariable("pwd") String pwd) {
        UserInfo userInfo = userService.queryByUsername(name);
        if (null == userInfo) {
            return new MyJsonResult(1, "用户名不存在", null, null);
        } else if (userInfo.getRole() < 1) {
            return new MyJsonResult(3, "您无权登录该系统", null, null);
        } else if (!pwd.equals(userInfo.getPassword())) {
            return new MyJsonResult(2, "密码错误", null, null);
        }
        return new MyJsonResult(0, null, null, null);
    }


    @PostMapping("/login")
    public String login(UserInfo userInfo, HttpSession session) {
        UserInfo existsUser = userService.queryByUsername(userInfo.getUsername());
        //将用户信息保存到session
        session.setAttribute("loginUser", existsUser);
        return "redirect:/main";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "redirect:/login";
    }
}
